package com.sophialex.health.record.common.dialog;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;

import com.sophialex.health.record.common.Messages;
import com.sophialex.health.record.common.util.HealthRecordContants;
import com.sophialex.health.system.frame.resource.RcpResourceManager;
import com.sophialex.health.system.frame.util.Assert;
import com.sophialex.health.system.frame.util.LayoutUtil;
import com.sophialex.health.system.frame.util.RefMethod;
import com.sophialex.health.system.frame.widgets.dbTable.DbTable;

/**
 * 字典弹出框基类
 * <p>Title:Health</p>
 * <p>CommonDlg</p>
 * 
 * Alex Apr 2, 2011 9:50:12 AM create
 * @author <a href='wanghao924@126.com'>Alex</a>
 * QQ: 873987060;
 * @version 1.0
 */
public abstract class CommonDlg extends Dialog {

	protected Object result = null;
	protected Shell shell;

	protected Button okBtn, cancelBtn;
	protected Label label;
	protected Text text;
	protected Composite composite_1;
	protected Composite composite;
	protected DbTable dbTable;
	protected Table table;
	protected String[] proStr;
	protected String[] filterPro;
	protected List list = new ArrayList();
	protected String filterStr = ""; 
	private Button button_add;
	private FormData formData_1;
	
	protected int type;

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public CommonDlg(Shell parent) {
		super(parent);
	}
	
	public void setTitileName(String title){
		this.setText(title);
	}
	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public Object open() {
		Display display = getParent().getDisplay();
		createContents();
		LayoutUtil.centerShell(display, shell);
		shell.open();
		initUI();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	protected void initUI() {
		text.setFocus();
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		shell.setLayout(new FormLayout());
		{
			composite = new Composite(shell, SWT.NONE);
			composite.setLayout(new FormLayout());
			{
				FormData formData = new FormData();
				formData.height = 38;
				formData.right = new FormAttachment(100);
				formData.bottom = new FormAttachment(100);
				formData.left = new FormAttachment(0);
				composite.setLayoutData(formData);
			}
			{
				cancelBtn = new Button(composite, SWT.NONE);
				cancelBtn.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						shell.close();
					}
				});
				{
					FormData formData = new FormData();
					formData.width = 58;
					formData.bottom = new FormAttachment(100, -6);
					formData.right = new FormAttachment(100, -10);
					cancelBtn.setLayoutData(formData);
				}
				cancelBtn.setText(Messages.CommonDlg_1);
				cancelBtn.setFocus();
			}
			{
				okBtn = new Button(composite, SWT.NONE);
				okBtn.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent e) {
						okPress();
					}
				});
				{
					formData_1 = new FormData();
					formData_1.right = new FormAttachment(cancelBtn, -6);
					formData_1.width = 58;
					formData_1.top = new FormAttachment(cancelBtn, 0, SWT.TOP);
					okBtn.setLayoutData(formData_1);
				}
				okBtn.setText(Messages.CommonDlg_2);
			}
			{
				label = new Label(composite, SWT.NONE);
				{
					FormData formData = new FormData();
					formData.top = new FormAttachment(0, 12);
					formData.left = new FormAttachment(0, 10);
					label.setLayoutData(formData);
				}
				label.setText(Messages.CommonDlg_3);
			}
			{
				text = new Text(composite, SWT.BORDER);
				{
					FormData formData = new FormData();
					formData.width = 106;
					formData.bottom = new FormAttachment(label, 4, SWT.BOTTOM);
					formData.left = new FormAttachment(label, 6);
					text.setLayoutData(formData);
				}
			}
		}
		{
			composite_1 = new Composite(shell, SWT.NONE);
			composite_1.setLayout(new FillLayout(SWT.HORIZONTAL));
			{
				FormData formData = new FormData();
				formData.bottom = new FormAttachment(composite);
				formData.right = new FormAttachment(composite, 0, SWT.RIGHT);
				formData.top = new FormAttachment(0);
				formData.left = new FormAttachment(composite, 0, SWT.LEFT);
				{
					if(type==HealthRecordContants.SHOW_ADD_PERSON_DIALOG_TYPE){
						button_add = new Button(composite, SWT.NONE);
						formData_1.left = new FormAttachment(button_add, 6);
						button_add.setText(Messages.CommonDlg_4);
						FormData fd_button_add = new FormData();
				
						fd_button_add.right = new FormAttachment(100, -138);
						fd_button_add.width = 58;
						fd_button_add.bottom = new FormAttachment(cancelBtn, 0, SWT.BOTTOM);
						button_add.setLayoutData(fd_button_add);
						button_add.addSelectionListener(new SelectionAdapter() {
							public void widgetSelected(SelectionEvent e) {
								addPress();
							}
						});
					}
				}
				composite_1.setLayoutData(formData);
			}
			{
				dbTable = new DbTable(composite_1, SWT.BORDER
						| SWT.FULL_SELECTION | SWT.VIRTUAL);
				table = dbTable.getTable();
				table.setHeaderVisible(true);
				table.setLinesVisible(true);
				dbTable.setAutoResizeColumn(true);
				dbTable.setSelectionBackground(RcpResourceManager.getColor(87,
						140, 0));
				dbTable.setRowheight(24);

			}
			createColumn();
			addListner();
			initData();
			setSize();
			setShellText();
		}

	}

	protected abstract void setSize();

	protected void setShellText() {

	};

	protected void okPress() {
		if (table.getSelectionCount() > 0) {
			result = table.getSelection()[0].getData();
			shell.close();
		}
	}
    protected  void openDialog(){};
    
	protected void addPress(){
		shell.close();
		openDialog();
		
		
	}
	
	protected void initData() {

		if (filterStr == null)
			filterStr = ""; //$NON-NLS-1$

		filtText(filterStr);
		text.setText(filterStr);
		text.setSelection(filterStr.length());
		table.setSelection(0);
	}

	private void addListner() {
		text.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				filtText(text.getText());
			}
		});
		table.addSelectionListener(new SelectionListener() {
			public void widgetSelected(SelectionEvent arg0) {
			}

			public void widgetDefaultSelected(SelectionEvent arg0) {
				okPress();
			}
		});
		text.addTraverseListener(new TraverseListener() {
			public void keyTraversed(TraverseEvent e) {
				if (e.keyCode == SWT.ARROW_DOWN) {
					jumpNext();
					e.doit = false;
				} else if (e.keyCode == SWT.ARROW_UP) {
					jumpUp();
					e.doit = false;
				} else if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {
					okPress();
					e.doit = false;
				}
			}
		});

	}

	protected void jumpUp() {
		int curIdx = table.getSelectionIndex();
		if (curIdx > 0) {
			table.setSelection(curIdx - 1);
		}
	}

	protected void jumpNext() {
		int curIdx = table.getSelectionIndex();
		if (curIdx < table.getItemCount() - 1) {
			table.setSelection(curIdx + 1);
		}
	}

	protected abstract void createColumn();

	/**
	 * 过滤表格数据
	 * 
	 * @param txt
	 */
	@SuppressWarnings("unchecked")
	public void filtText(String txt) {
		if (filterPro == null)
			filterPro = (String[]) dbTable.getColumnProperties();
		List alist = exactFilter(list, filterPro, txt);
		dbTable.setInput(alist);
		table.setSelection(0);
	}

	/**
	 * 精确匹配和模糊匹配放一起，先左精确完，后模糊匹配
	 * 
	 * @param <T>
	 * @param list
	 * @param firstProperties
	 * @param text
	 * @return
	 */
	public static <T> List<T> exactFilter(List<T> list,
			String[] firstProperties, String text) {
		if (firstProperties == null)
			return null;
		List<T> list1 = new ArrayList<T>();
		List<T> list2 = new ArrayList<T>();
		if (Assert.isNull(text))
			return list;
		if (Assert.isNull(list))
			return list;
		try {
			int idx = -1;
			T obj = null;
			for (T t : list) {
				obj = null;
				// if(l.contains(t))continue;
				Object o;
				for (String s : firstProperties) {
					o = null;
					if (s.contains(".")) { //$NON-NLS-1$
						StringTokenizer st = new StringTokenizer(s, ".", false); //$NON-NLS-1$
						o = t;
						while (st.hasMoreElements()) {
							String str = (String) st.nextElement();
							String getMethod = RefMethod.gainGetMethod(str);
							o = RefMethod.invokeGetMethod(o, getMethod);
						}
					} else {
						String getMethod = RefMethod.gainGetMethod(s);
						o = RefMethod.invokeGetMethod(t, getMethod);
					}
					if (o != null) {
						idx = (o.toString()).toLowerCase().indexOf(
								text.toLowerCase());
						if (idx == 0) {
							list1.add(t);
							obj = null;
							break;
						} else if (idx > 0 && obj == null) {
							obj = t;
						}
					}
				}
				if (obj != null)
					list2.add(t);
			}
			list1.addAll(list2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list1;
	}
}
